package com.jihox.abookpro.uploader;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jihox.abookpro.MyApplication;
import com.jihox.abookpro.MyUncaughtExceptionHandler;
import com.jihox.abookpro.R;
import com.jihox.abookpro.SubmitSuccessActivity;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.uploader.CustomMultipartEntity.ProgressListener;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.FileUtil;
import com.jihox.abookpro.util.NetStatus;

public class UploadService extends Service {

	public static final int MAX_PROGRESS = 100;
	public static final String TAG = "UploadService";
	private Long totalSize;
	private LinkedList<Order> ordersToUpload;
	private int dialogWidth =600;
	//wifi 环境上传  true，非wifi环境上传 false。
	private boolean WifiUpload=true;

	private final int UPLOAD_BLOCK_SIZE = 1024;
	/**开始上传*/  
    public final static int THREAD_BEGIN = 1;  
    /**上传结束*/  
    public final static int THREAD_FINISHED = 2;  
    /**报告进度*/  
    public final static int THREAD_REPORT_PROGRESS = 3;     
    public final static int THREAD_NO_WIFI = 4;
    /** 
     * 更新进度的回调接口 
     */  
    private OnProgressListener onProgressListener;  
    
	public boolean isPaySuccessActivityActive() {
		SharedPreferences sp = getSharedPreferences("PAYSUCCESSACTIVITYINFO", MODE_PRIVATE);
		return sp.getBoolean("active", false);
	}
	
	public void setWifiUpload(boolean wifiUpload) {
		WifiUpload = wifiUpload;
	}
	
	public boolean isOrderUploading(String orderId){
		Iterator<Order> it = ordersToUpload.iterator();
		while( it.hasNext())
		{
			Order order= it.next();
			if (orderId.equals(order.getOrderId())){
				return true;
			}
		}
		return false;
	}
	
	/** 
     * 注册回调接口的方法，供外部调用 
     * @param onProgressListener 
     */  
    public void setOnProgressListener(OnProgressListener onProgressListener) {  
        this.onProgressListener = onProgressListener;  
    }
	
	class MyRunnable implements Runnable {
		private Order mTask;
		private HttpPost httpPost;
		private static final int REQUEST_TIMEOUT = 10*1000;		//设置请求超时10秒钟  
		private static final int SO_TIMEOUT = 10*1000;  		//设置等待数据超时时间10秒钟  
		   
		public MyRunnable(Order order) {
			super();
			this.mTask = order;
			this.httpPost=new HttpPost(
					ConfigProperties.getBlockUploadServerUrl());;
		}
		
		@Override
		public void run() {
			
			updateOrderStatus(mTask);
						
			// 如果是续传 则要先获取已上传的文件大小
			if(!mTask.isNewOrder())
			{
				long uploadedSize = -1;
				for(int i = 0 ; i < 3 ; i++){
					uploadedSize = getFinishedSize();
					// 获取上传大小成功则退出，否则执行3次
					if(uploadedSize >= 0 || mTask.isFileUploaded()){
						break;
					}
				}
				if( uploadedSize >= 0){
					mTask.setUploadedSize(uploadedSize);
				} else if (!mTask.isFileUploaded()){
					// 3次获取文件已上传大小都失败，则任务失败
					mTask.setOrderStatus(Order.ORDER_STATUS_UPLOAD_FAILED);
					updateOrderStatus(mTask);
	                Message message = new Message();  
	                message.what = THREAD_FINISHED;  
	                taskHandler.sendMessage(message); 
					return;
				}
			}
			// 上传任务的出错次数
			int errorCnt = 0;
			// 循环直到文件块全部上传完
			while(!mTask.isFileUploaded())
			{
				long uploadedSize = mTask.getUploadedSize();
				File file = null;
				try {
					// 获取待上传的文件块
					file = getBlockUploadFile(uploadedSize);
					// 获取不到则代表已经上传完了
					if(file == null){
						//已经没有需要上传的文件块了
						mTask.setFileUploaded(true);
					}else {
						//在用户没有指定可以用wifi以外的网络传输的情况下
						if(WifiUpload){
							//判断当前是否是wifi网络
							boolean isWifi = NetStatus.isWifi(getApplicationContext());
							//无wifi状态，询问用户是否继续
							if(!isWifi)
							{
								//弹出NoWifi 的对话框
								Message message = new Message();  
				                message.what = THREAD_NO_WIFI;  
				                taskHandler.sendMessage(message); 
								// 停止上传
								return;
							}
						}
						
						while(errorCnt<3){
							//上传文件,成功则失败计数清0，删除临时文件
							if(uploadBlockFile(file)){
								errorCnt = 0;
								file.delete();
								break;
							}else{
								// 上传失败增加计数
								errorCnt++;
							}
						}
						
						// 失败3次，则任务失败，退出上传
						if(errorCnt > 2){
							mTask.setOrderStatus(Order.ORDER_STATUS_UPLOAD_FAILED);
							updateOrderStatus(mTask);
							Message message = new Message();  
			                message.what = THREAD_FINISHED;  
			                taskHandler.sendMessage(message); 
			                return;
						}
					}
				} catch (IOException e) {
					errorCnt++;
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					if (errorCnt>2){
						MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "upload error");
						mTask.setOrderStatus(Order.ORDER_STATUS_UPLOAD_FAILED);
						updateOrderStatus(mTask);
						Message message = new Message();  
		                message.what = THREAD_FINISHED;  
		                taskHandler.sendMessage(message); 
		                return;
					}
				}
			}
			//上传成功了
			//删除文件
			if(mTask.isFileUploaded())
			{
				if (updateWorkStatus()){
					mTask.setOrderStatus(Order.ORDER_STATUS_UPLOADED);
					
					File originalFile = new File(mTask.getZipFilePath());
					if (originalFile.exists()) {
						originalFile.delete();
					}
				}else{
					mTask.setOrderStatus(Order.ORDER_STATUS_UPLOAD_FAILED);
				}
			}else{
				mTask.setOrderStatus(Order.ORDER_STATUS_UPLOAD_FAILED);
			}
			updateOrderStatus(mTask);
			Message message = new Message();  
            message.what = THREAD_FINISHED;  
            taskHandler.sendMessage(message); 
		}
		
		private boolean uploadBlockFile(File file)
		{
			BasicHttpParams httpParams = new BasicHttpParams();  
		    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
		    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());
		
			boolean isSuccess = false;
			try {
				CustomMultipartEntity multipartContent = new CustomMultipartEntity(
					new ProgressListener() {
						@Override
						public void transferred(long num) {
							mTask.setUploadProgress((int) (((mTask.getUploadedSize() + num) / (float) totalSize) * 100));
							Log.d("FileUploadService", "getUploadProgress:" +mTask.getUploadProgress());
							Message message = new Message();  
			                message.what = THREAD_REPORT_PROGRESS;  
			                taskHandler.sendMessage(message); 
						}
					});

				multipartContent.addPart("blockcrc",new StringBody(FileUtil.getCRC32(file.getPath())));
				multipartContent.addPart("filesize",
						new StringBody(String.valueOf(new File(mTask.getZipFilePath()).length())));
				if (mTask.isOnlyLastBlock()){
					if (mTask.getZipFileCrc()==null){
						mTask.setZipFileCrc(FileUtil.getCRC32(mTask.getZipFilePath()));
					}
					
					multipartContent.addPart("filecrc", new StringBody(mTask.getZipFileCrc()));
				}
				multipartContent.addPart("a", new FileBody(file));
				
				httpPost.setEntity(multipartContent);
				HttpResponse response = httpclient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
					
					JSONObject result = new JSONObject(res);
					isSuccess = result.getBoolean("success");
					if (isSuccess){
						mTask.setUploadedSize(mTask.getUploadedSize()+ UPLOAD_BLOCK_SIZE* 1024);
						String fileUrl = result.getString("fileurl");
						if (fileUrl!=null && !fileUrl.isEmpty()){
							mTask.setUploadedFileUrl(fileUrl);
							updateOrderFileUrl(mTask);
						}else{
							MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(new Exception("fileurl is null"), "uploadBlockFile (fileurl is null)");
						}
						
					}else{
						String msg = result.getString("msg");
						// 如果整个文件的校验不对，则需要重传
						if (msg != null && msg.equals("J500")){
							mTask.setUploadedSize(0);
							mTask.setOnlyLastBlock(false);
						}
					}
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				httpclient.getConnectionManager().shutdown();
			}
			
			return isSuccess;
		}

		private Long getFinishedSize() {

			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(
					ConfigProperties.getUploadFinishedSizeUrl().replace("{}",mTask.getOrderId() + "_" + mTask.getWorksn()+ ".zip")
							);
			UserHelper helper = new UserHelper();
			httpGet.setHeader("username", helper.getUserName());
			httpGet.setHeader("password", helper.getPassword());
			boolean isSuccess = false;
			long finishedSize = (long) -1;
			try {

				HttpResponse response = httpclient.execute(httpGet);
				HttpEntity resEntity = response.getEntity();
				
				if (resEntity != null) {
					
					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
					
					JSONObject result = new JSONObject(res);
					isSuccess = result.getBoolean("success");
					
					if (isSuccess) {
						mTask.setFileUploaded(true);
						String fileUrl = result.getString("fileurl");
						if (fileUrl!=null && !fileUrl.isEmpty()){
							mTask.setUploadedFileUrl(fileUrl);
							updateOrderFileUrl(mTask);
						}else{
							MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(new Exception("fileurl is null"), "getFinishedSize (fileurl is null)");
						}
					}else{
						finishedSize = result.getLong("uploadedsize");
					}
					resEntity.consumeContent();
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				httpclient.getConnectionManager().shutdown();
			}
		
			return finishedSize;
		}
		
		//自定义每个上传块为  1 M
		@SuppressWarnings("resource")
		private File getBlockUploadFile(long uploadedSize) throws IOException {
			// 建立输入流
			File inFile = new File(mTask.getZipFilePath());
			File outFile = new File(inFile.getParentFile(), mTask.getOrderId()
					+ "_" + mTask.getWorksn() + ".zip");

			if(totalSize == null)
			{
				totalSize = inFile.length();
			}
			
			if(outFile.exists()){
				outFile.delete();
			}
			Log.d(TAG,"inFile = " + inFile.length()+"");
			RandomAccessFile in = new RandomAccessFile(inFile, "r");
			RandomAccessFile out = new RandomAccessFile(outFile, "rw");
			byte[] b = new byte[1024];
			int n = 0;
			in.seek(uploadedSize);// 从指定位置读取
			
			//文件已经上传完毕
			if(in.getFilePointer() > inFile.length())
			{
				Log.d(TAG,"return null");
				return null;
			}
			int i=0;
			while (i < UPLOAD_BLOCK_SIZE
					&& (n = in.read(b)) != -1) {
				out.write(b, 0, n);
				i++;
			}

			if (in.read(b) == -1){
				mTask.setOnlyLastBlock(true);
			}
			
			in.close();
			out.close();
			Log.d(TAG, outFile.length()+"");
			return outFile;
		}
		
		private boolean updateWorkStatus() {

			boolean isSuccess = false;
			
			if (mTask.getUploadedFileUrl()==null || mTask.getUploadedFileUrl().isEmpty()){
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(new Exception(), "updateWorkStatus error(fileurl is null)");
				return isSuccess;
			}
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(
					ConfigProperties.getUploadedWorkUrl().replace("{}", mTask.getWorksn())
							);
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("url", mTask.getUploadedFileUrl()));
			
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				
				HttpResponse response = httpclient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();
				
				if (resEntity != null) {

					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());

					JSONObject result = new JSONObject(res);
					isSuccess = result.getBoolean("success");
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "updateWorkStatus error");
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "updateWorkStatus error");
				e.printStackTrace();
			} catch (IOException e) {
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "updateWorkStatus error");
				e.printStackTrace();
			} catch (ParseException e) {
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "updateWorkStatus error");
				e.printStackTrace();
			} catch (JSONException e) {
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "updateWorkStatus error");
				e.printStackTrace();
			} catch (Exception e) {
				MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "updateWorkStatus error");
				e.printStackTrace();
			} finally {
				httpclient.getConnectionManager().shutdown();
			}
			return isSuccess;
		}
	}

	public boolean isAppOnForeground() {  
	    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
	    if (activityManager == null) {  
	        return false;  
	    }  
	    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();  
	    if (appProcesses == null) {  
	        return false;  
	    }  
	    
	    for (RunningAppProcessInfo appProcess : appProcesses) {  
	        if (appProcess.processName.equals("com.jihox.abookpro")){
                if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
                	return true;  
                }
	        }  
	    }  

	    return false;  
	}

	@Override
	public void onCreate() {
		ordersToUpload = new LinkedList<Order>();
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "onStartCommand() executed");
		if (intent !=null){
			WifiUpload = intent.getBooleanExtra("UploadWithWifi", true);
			dialogWidth = intent.getIntExtra("DialogWidth",600);
		}
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	public void addUploadTask(Order order){
		order.setNewOrder(order.getOrderStatus() == Order.ORDER_STATUS_PAID);
		order.setOrderStatus(Order.ORDER_STATUS_UPLOAD_WAITING);
		updateOrderStatus(order);
		ordersToUpload.add(order);
		//开始下一个任务  
        Message message = new Message();  
        message.what = THREAD_BEGIN;  
        taskHandler.sendMessage(message); 
	}
	
	private Handler taskHandler = new Handler(){  
        @Override  
        public void handleMessage(Message msg) {  
        	List<String> waitingOrders;
        	Order order;
        	switch(msg.what){  
	            case THREAD_BEGIN:  
	            	synchronized(this){
	            		if (ordersToUpload.get(0).getOrderStatus()== Order.ORDER_STATUS_UPLOAD_WAITING){
		            		// 开始上传，更新状态
		            		ordersToUpload.get(0).setOrderStatus(Order.ORDER_STATUS_UPLOADING);
							Runnable runnable = new MyRunnable(ordersToUpload.get(0));
							new Thread(runnable).start();
						}
	            	}
	                break;  
	            case THREAD_FINISHED:  
	            	waitingOrders = new ArrayList<String>();
	                for (int i=1; ordersToUpload.size()>i;i++){
	                	waitingOrders.add(ordersToUpload.get(i).getOrderId());
	                }
	                order = ordersToUpload.get(0);
	                if(onProgressListener != null){  
	                	if (!isAppOnForeground() && order.getOrderStatus() == Order.ORDER_STATUS_UPLOADED){
	                		showNotification(order);
	                	}
                        onProgressListener.onProgress(order.getOrderId(),order.getOrderStatus(),order.getUploadProgress(),waitingOrders);  
                    } else if (order.getOrderStatus() == Order.ORDER_STATUS_UPLOADED){
                		if (isAppOnForeground()){
    						showDialog(order.getOrderId());
    					}else{
    						showNotification(order);
    					}
            		}
	                
	                ordersToUpload.remove(0);
	            	//开始下一个任务  
	                if (ordersToUpload.size()>0){
	                	Message message = new Message();  
		                message.what = THREAD_BEGIN;  
		                sendMessage(message); 
	                }
	                break;
	            case THREAD_NO_WIFI:
	            	ShowNoWifiPauseDialog();
	            	break;
	            case THREAD_REPORT_PROGRESS:
	                waitingOrders = new ArrayList<String>();
	                for (int i=1; ordersToUpload.size()>i;i++){
	                	waitingOrders.add(ordersToUpload.get(i).getOrderId());
	                }

	                if(onProgressListener != null){  
	                	order = ordersToUpload.get(0);
                        onProgressListener.onProgress(order.getOrderId(),order.getOrderStatus(),order.getUploadProgress(),waitingOrders);  
                    }  
	            	break;
            }  
            
        }    
    };  

	@Override
	public void onDestroy() {
		Log.d(TAG, "onDestroy() executed---------------------------------------------------------------------------------");
		updateOrdersStatus();
		//this.unregisterConnectChangeReceiver();
		super.onDestroy();
		System.exit(0);
	}

	private void updateOrderStatus(Order order) {
		OrderDAO dao = new OrderDAO(this.getApplicationContext());
		dao.updateOrderStatus(order);
	}
	
	private void updateOrderFileUrl(Order order) {
		OrderDAO dao = new OrderDAO(this.getApplicationContext());
		dao.updateOrderFileUrl(order);
	}
	
	private void updateOrdersStatus() {
		Iterator<Order> it = ordersToUpload.iterator();
		while( it.hasNext())
		{
			Order order= it.next();
			if (order.isNewOrder() && order.getOrderStatus() == Order.ORDER_STATUS_UPLOAD_WAITING){
				order.setOrderStatus(Order.ORDER_STATUS_PAID);
			}else{
				order.setOrderStatus(Order.ORDER_STATUS_UPLOAD_FAILED);
			}
			updateOrderStatus(order);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, "onBind() executed");
		return new UploadBinder();
	}

	public class UploadBinder extends Binder {
		/**
		 * 获取当前Service的实例
		 * 
		 * @return
		 */
		public UploadService getService() {
			return UploadService.this;
		}
	}
	
	private void showDialog(String orderId) {
		final Dialog dialog = new Dialog(MyApplication.getInstance().currentActivity(), R.style.JHDialog);
        //设置它的ContentView
        dialog.setContentView(R.layout.dialog_general);
        Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
        Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
        TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);
        
        buttonOK.setBackgroundResource(R.drawable.grey_style);
        buttonCancel.setBackgroundResource(R.drawable.grey_style);
        buttonOK.setText(R.string.T_Ok);
        
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);  // , 1是可选写的
        lp.setMargins(0, 0 ,0, 0); 
        
        buttonOK.setLayoutParams(lp);
        buttonCancel.setVisibility(View.GONE);
        dialogTitle.setText(R.string.T_Upload_Success);
        dialogMessage.setText(getResources().getString(R.string.T_Upload_Success_With_OrderID) + orderId);
        dialog.setCanceledOnTouchOutside(false);
        buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
        
        dialog.show();
        
	}

	private void showNotification(Order task) {
		// 获取到通知管理器
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		// 定义内容
		int notificationIcon = R.drawable.icon;
		CharSequence notificationTitle = getResources().getString(R.string.T_Upload_Success_With_OrderID) + task.getOrderId();
		long when = System.currentTimeMillis();

		Notification notification = new Notification(notificationIcon,
				notificationTitle, when);

		notification.defaults = Notification.DEFAULT_ALL;

		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setClass(getApplicationContext(),
				SubmitSuccessActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		Bundle bundle = new Bundle();
		bundle.putString("OrderCode", task.getOrderId());
		bundle.putString("OrderDeliveryCycle",
				String.valueOf(task.getOrderDeliveryCycle()));

		intent.putExtras(bundle);
		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, intent, 0);
		notification.setLatestEventInfo(getApplicationContext(), getResources().getString(R.string.T_Upload_Success),
				getResources().getString(R.string.T_Upload_Success_With_OrderID) + task.getOrderId(), pendingIntent);
		//notification.flags |= Notification.FLAG_AUTO_CANCEL;
		if (notification != null) {
			Log.e("notifacation", "notifacation is ok");
			mNotificationManager.notify(1000, notification);
		}
	}
	
	//显示是否上传的对话框
	private void ShowNoWifiPauseDialog(){
		final Dialog dialog = new Dialog(MyApplication.getInstance().currentActivity(), R.style.JHDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
        //设置它的ContentView
        dialog.setContentView(R.layout.dialog_general);
        Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
        Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
        TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);
        buttonOK.setBackgroundResource(R.drawable.green_style);
        buttonCancel.setBackgroundResource(R.drawable.grey_style);
        dialogTitle.setText(R.string.T_DataFlow_Remind);
        Order task = ordersToUpload.get(0);
        File file = new File(task.getZipFilePath());
		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		dialogMessage.setText(getResources().getString(R.string.T_Net_Use_Remind)
				+ df.format((double) ((file.length()* (float)(100-task.getUploadProgress())/100) / 1024 / 1024)) + getResources().getString(R.string.T_Net_Use_Continue));
        buttonOK.setText(R.string.T_Continue_Text);
        buttonCancel.setText(R.string.T_Later_Upload);
        buttonOK.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				WifiUpload = false;
				ordersToUpload.get(0).setOrderStatus(Order.ORDER_STATUS_UPLOAD_WAITING);
				
				//开始下一个任务  
                Message message = new Message();  
                message.what = THREAD_BEGIN;  
                taskHandler.sendMessage(message); 
			}
        });
		buttonCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				WifiUpload = true;
				
				updateOrdersStatus();
				//关闭所有的上传任务
				for (Order order : ordersToUpload){
					Message message = new Message();  
	                message.what = THREAD_FINISHED;  
	                taskHandler.sendMessage(message); 
				}
			}
		});
		dialog.show();
	}
	
}
